local InvasionTeamItem = require("View/UIInvasion/SubPanel/InvasionTeamItem")
local InvasionDamageItem = require("View/UIInvasion/SubPanel/InvasionDamageItem")
local InvasionBossItem = require("View/UIInvasion/SubPanel/InvasionBossItem")
local InvasionStatisticsItem = require("View/UIInvasion/SubPanel/InvasionStatisticsItem")

---@class UIInvasionBattle : UIBase
UIInvasionBattle = UIBase.New(PanelResNames.UIInvasionBattle)
local t = UIInvasionBattle
local STARTBATTLE_SOUND=3002
local setTimer = nil
function t.Init(func)
    UIBase.Init(t, func)
end

function t:OnCreate()
    AddUIPackageDepend(PanelNames.UIInvasionBattle,"FUI/BattleItems")
    self.btnBack = self:GetChild("btnBack")
    local bossName = self:GetChild("bossName")
    local bossLevel = self:GetChild("bossLevel")
    local bossBloodBar = self:GetChild("bossBloodBar")
    local bossHpText = self:GetChild("damage",bossBloodBar)
    local bossGraph = self:GetChild("boss")
    local bossBg = self:GetChild("n46")
    local maxController = self:GetController("max")
    self.turnBar = self:GetChild("timeBar")
    self.turnText = self:GetChild("text_round")
    self.btnStatisticOpen = self:GetChild("btnOpen")
    self.ctrlStatisticOpen = self:GetController("showInfo")
    self.teamSkillItemList = {}
    self.transitionScale = self:GetTransition("effect_Camera")
    self.isPlayTranScale = 0
    ---@type InvasionTeamItem[]
    self.teamItemList = {}
    for i = 1,4 do
        local c = self:GetChild("skill"..i)
        if c ~= nil then
            table.insert(self.teamSkillItemList,c)
        end
    end
    self.effectLoader = self:GetChild("effect")
    local _list = {}
    for i = 1,4 do
        local obj = self:GetChild("playerInfo"..i)
        table.insert(_list,obj)
    end
    for i = 1,4 do
        ---@type InvasionTeamItem
        local com = InvasionTeamItem.New(self:GetChild("team"..i))
        table.insert(self.teamItemList,com)
    end
    ---@type InvasionStatisticsItem
    self.statisticsItem = InvasionStatisticsItem.New()
    self.statisticsItem:InitComponent(_list)
    self.bossItem = InvasionBossItem.New()
    self.bossItem:InitComponent(bossName,bossLevel, bossBloodBar,bossHpText,bossGraph,bossBg, nil, maxController)
    self.timeBar = self:GetChild("timeBar")
    self.btnChange=self:GetChild("btnChange")
    self.btnSetting=self:GetChild("btnSetting")
    self.btnApply=self:GetChild("btnApply")
    self.btnCall=self:GetChild("btnCall")
    self.btnChat=self:GetChild("btnChat")
    self.btnFind=self:GetChild("btnFind")
    self.btnLeave=self:GetChild("btnLeave")
    self.typeCtrl=self:GetController("type")
    self.teamIdText=self:GetChild("teamId")
    self.btnReward=self:GetChild("btnReward")
    self.btnRewardUp=self:GetChild("btnRewardUp")
    self.txtRewardUp = self:GetChild("text_num")
    self.upRewardCtrl=self:GetController("up")
    self.btnRank=self:GetChild("btnRank")
    self.battleUICtrl=self:GetController("battle")
    self.battleEft=self:GetChild("effect_kaizhan").wrapTarget
    self.btnHelp=self:GetChild("help")
    self.resultCtrl=self:GetChild("Com_result"):GetController("result")
    self.resultComp=self:GetChild("Com_result")
    self.ctrlSingle = self:GetController("single")
    self.jumpCtrl=self:GetController("jump")
    self.jumpTransition=self:GetTransition("effect_jump")
    self.aniEff = self.btnReward:GetTransition("effect_up")
    self.weekNumCtrl = self:GetController("weeknum")
    self:RegisterOnClick(self.btnBack,self.ClickBack)
    self:RegisterOnClick(self.btnChange,self.OnClickBtnChange)
    self:RegisterOnClick(self.btnApply,self.OnClickBtnApply)
    self:RegisterOnClick(self.btnSetting,self.OnClickBtnSetting)
    self:RegisterOnClick(self.btnCall,self.OnClickBtnCall)
    self:RegisterOnClick(self.btnChat,self.OnClickBtnChat)
    self:RegisterOnClick(self.btnFind,self.OnClickBtnFindTeam)
    self:RegisterOnClick(self.btnLeave,self.OnClickBtnLeave)
    self:RegisterOnClick(self.btnStatisticOpen,self.ClickStatisticOpen)
    self:RegisterOnClick(self.btnReward,self.OnClickBtnReward)
    self:RegisterOnClick(self.btnRewardUp,self.OnClickBtnRewardUp)
    self:RegisterOnClick(self.btnRank,self.OnClickBtnRank)
    self:RegisterOnClick(self.btnHelp,self.OnClickBtnHelp)
    self:RegisterOnClick(self.teamIdText,self.OnClickIdText)
    self:InitStageReward()
    self:InitBossDesc()
    self.staticId = 0
    ---@type InvasionDamageItem[]
    self.damageItemList = {}
    ---@type InvasionDamageItem[][]
    self.damageCacheList = {{},{}}
    self:AddEvent()
    TBS.Battle.Start()
    self:TimeCall(self.Update,100,-1)
    self:TimeCall(self.CheckIsClose,1000,-1)
    self:InitTeam()
    --self:ShowBattleStart()
    self.jumpCtrl.selectedIndex=1
    self:SetBattleUICtrl(1)
    --if self:IsBattleValid() then
   --     self:ShowBattleStart()
   -- end
    self.mainReward = self:GetChild("mainReward")
    logicMgr.FuncOpenManager.refreshMainReward(self.mainReward,Config.FuncOpenType.InvasionBattle)
    if setTimer then
        utimer.remove(setTimer)
        setTimer = nil
    end
    setTimer = utimer.frameCall(function()
        if Time.timeScale > 1 then
            Time.timeScale = 1
        end
    end,-1)
end
function t:InitBossDesc()
    local bossDescCom=self:GetChild("com_bossskill")
    self.bossComs={}
    for i=1,3 do
        local name=bossDescCom:GetChild("Text_skilltips0"..tostring(i))
        local desc=bossDescCom:GetChild("Text_skill0"..tostring(i))
        table.insert(self.bossComs,{name,desc})
    end
    self.btnBossClose=bossDescCom:GetChild("n13")
    self.bossSkillCtrl=self:GetController("BossSkill")
    self.bossSkillCtrl.selectedIndex=0
    self.btnBossSkill=self:GetChild("btn_bossskill")
    self:RegisterOnClick(self.btnBossSkill,self.OnClickBtnBossSkill)
    self:RegisterOnClick(self.btnBossClose,self.OnClickBtnBossSkill)
end
function t:OnClickBtnBossSkill()
    if self.bossSkillCtrl.selectedIndex==0 then
        self.bossSkillCtrl.selectedIndex=1
    else
        self.bossSkillCtrl.selectedIndex=0
    end
end
function t:InitStageReward()
    self.rewardCtrl=self:GetController("reward")
    self.rewardList=self:GetChild("listReward")
    self.btnShow=self:GetChild("btnShowStageReward")
    self.btnGet=self:GetChild("btnGetReward")
    self:GetChild("TaskTitle").text=getLanguage("ChapterRewardTips4")
    self:RegisterOnClick(self.btnShow,self.OnClickBtnShow)
    self:RegisterOnClick(self.btnGet,self.OnClickBtnGet)
end
function t:OnClickBtnShow()
    showUI(PanelNames.UIInvasionReward)
end
function t:OnClickBtnGet()
    InvasionHandler.ReqTeamSectionReward()
end
function t:RefreshRewardList()
    local stage=MapManager.getMapId()
    local level=InvasionHandler.GetMyBossLv()-1
    local receiveId=InvasionHandler.receiveID
    local rewardData=logicMgr.InvasionManager.getInvasionRewards(receiveId)
    local reward={}
    if rewardData[1] then
        if rewardData[1] and level>=rewardData[1].f_CollocationId then
            self.rewardCtrl.selectedIndex=1
            reward=rewardData[1].f_CollocationReward
            logicMgr.CostManager.RefreshItemList(self.rewardList,reward)
        else
            self.rewardCtrl.selectedIndex=0
            logicMgr.CostManager.RefreshItemList(self.rewardList,rewardData[1].f_CollocationReward)
            local offset=rewardData[1].f_CollocationId-level
            self:GetChild("TaskTitle02").text=string.format(getLanguage("InvasionNext"),rewardData[1].f_CollocationId)
        end
    else
        self.rewardCtrl.selectedIndex = 2
    end
end

function t:CheckIsClose()
    if not logicMgr.InvasionManager.IsOpen() then
        logicMgr.InvasionManager.QuitBattle()
    end
end
function t:RequestReport()
    --local data = InvasionHandler.teamData
    --TBS.VirtualServer.RequestReport(data.oss,data.devOss, data.warPath)
    InvasionHandler.ReqInitTeamBoss(1)
end
function t:IsBattleValid()
    return not string.IsNilOrEmpty(InvasionHandler.teamData.warPath)
end
function t:Refresh()
    if InvasionHandler.IsMyRoom() then
        self.typeCtrl.selectedIndex=0
    else
        self.typeCtrl.selectedIndex=1
    end
    self.teamIdText.text=InvasionHandler.teamData.teamId
    self:RefreshTeamState()
    self:RefreshRewardList()
end
function t:OnClickBtnHelp()
    --local title=getLanguage("InvasionRulesTitle")
    --local desc=getLanguage("InvasionRules")
    logicMgr.UIShowManager.ShowCommonTips("InvasionRulesTitle", "InvasionRules", "FunctionStory310")
end
function t:OnClickBtnReward()
    --showUI(PanelNames.UIInvasionReward)
    InvasionHandler.ReqTeamBossReward()
end
function t:OnClickBtnRewardUp()
    --1，判断是否在高收益阶段  2，判断次数是否还够
    local countRemain, highRewardEndTime = logicMgr.InvasionManager.GetInvasionHighRewardInfo()
    local countTime = highRewardEndTime - HelperFunc.GetServerTime()
    local totalTimePerWeek = dataTable.getDataTableByStringId("t_global", 629, "f_int_value") or 0
    if countRemain <= 0  then
        UISysTips.AddMsg(getLanguage("TeamBossUpTip01"))
        return
    end
    if countTime > 0 then
        UISysTips.AddMsg(getLanguage("TeamBossUpTip02"))
        return
    end
    local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop)
    pop.Init("124",function(b)
        if b then
            self.aniEff:Play()
            InvasionHandler.ReqOpenHighReward(1) --0，请求信息  1，开启高收益
            local dic = {}
            dic.remain_num = countRemain
            TAManager.TrackByDictionary("invasion_high_mode",dic)
        end
    end,countRemain, totalTimePerWeek)
end
function t:OnClickBtnRank()
    InvasionHandler.ReqTeamBossRankInfo()
end
function t:OnClickIdText()
    UnityEngine.GUIUtility.systemCopyBuffer = self.teamIdText.text
    UISysTips.AddMsg(getLanguage("CopySuccess"))
end
function t:OnClickBtnChange()
    showUI(PanelNames.UIInvasionTeam)
end
function t:OnClickBtnApply()
    showUI(PanelNames.UITeamApply)
end
function t:OnClickBtnSetting()
    showUI(PanelNames.UITeamSetting)
end
function t:OnClickBtnCall()
    logicMgr.InvasionManager.SendWorldInvitation(0)
end
function t:OnClickBtnChat()
    showUI(PanelNames.UIChatPanel,Config.MsgChannel.InvasionTeam,nil,true)
end
function t:OnClickBtnFindTeam()
    showUI(PanelNames.UIInvasionTeamList)
end
function t:OnClickBtnLeave()
    showUI(PanelNames.UICommonPop,"69",function(flag)
        if flag then
            InvasionHandler.ReqQuitTeamBoss()
        end
    end)
end
function t:ClickStatisticOpen()
    if self.ctrlStatisticOpen.selectedIndex == 0 then
        self.ctrlStatisticOpen.selectedIndex = 1
    else
        self.ctrlStatisticOpen.selectedIndex = 0
    end
end
function t:AddEvent()
    self:RegisterEvent(TBS.Config.Event.PlayerHpChanged,self.PlayerHpChanged)
    self:RegisterEvent(TBS.Config.Event.DamageShow,self.DamageShow)
    self:RegisterEvent(TBS.Config.Event.BossReleaseSkill,self.BossReleaseSkill)
    self:RegisterEvent(TBS.Config.Event.BattleRestart,self.BattleRestart)
    self:RegisterEvent(TBS.Config.Event.ActorDead,self.ActorDead)
    self:RegisterEvent(TBS.Config.Event.BattleLoadDone,self.BattleLoadDone)
    self:RegisterEvent(TBS.Config.Event.ScreenShake,self.ScreenShake)
    self:RegisterEvent(TBS.Config.Event.LeaderReleaseSkill,self.LeaderReleaseSkill)
    self:RegisterEvent(TBS.Config.Event.NeedUIPos,self.SendUIScreenPosToBattle)
    self:RegisterEvent(TBS.Config.Event.BattleFinished,self.BattleFinished)
    self:RegisterEvent(TBS.Config.Event.BattleTurnStart,self.BattleTurnStart)
    self:RegisterEvent(Config.EventType.InvasionTeamDataChange,self.Refresh)
    self:RegisterEvent(Config.EventType.InvasionChangeBulletState,self.SetBulletVisible)
    self:RegisterEvent(Config.EventType.InvasionStageRewardChange,self.RefreshRewardList)
    self:RegisterEvent(Config.EventType.InvasionReGetWarInfo,self.TryGetBattleReport)
    self:RegisterEvent(Config.EventType.InvasionFirstWar,self.StartFirstWar)
    self:RegisterEvent(Config.EventType.InvasionOpenHighReward,self.RefreshHighRewardState)
end
function t:OnEnable()
    self:Refresh()
    self:InitBarrage()
    self:RefreshHookRewardState()
    self:RefreshHighRewardState()
    self:TimeCall(self.RefreshHookRewardState,5000,-1)
    AudioManager.Play(31)
    if UIRedDots then
        UIRedDots.addViewListen(PanelNames.UIInvasionBattle, "UIInvasionBattle_btnReward",self.btnReward, Config.RedDotsType.HookReward);
    end
    Time.timeScale = 1
end
function t:OnDisable()
    InvasionHandler.refLevel=0
    self:ClearBattleStartTimer()
    self:ClearBattleReportTimer()
    self:ClearJumpTimer()
    self:ClearBarrage()
    if UIRedDots then
        UIRedDots.removeViewEvent(PanelResNames.UIInvasionBattle)
    end
    if setTimer then
        utimer.remove(setTimer)
        setTimer = nil
    end
end
function t:OnDestroy()
    TBS.Battle.Leave()
    TBS.VirtualServer.OnDestroy()
    if self.damageItemList then
        for k,v in pairs(self.damageItemList) do
            v:Destroy()
        end
    end
    if self.damageCacheList then
        for _type,_list in pairs(self.damageCacheList) do
            for k,v in pairs(_list) do
                v:Destroy()
            end
        end

    end
    if self.teamItemList then
        for k,v in pairs(self.teamItemList) do
            v:Destroy()
        end
    end
    self.damageItemList = nil
    self.damageCacheList = nil
    if self.bossItem then
        self.bossItem:Destroy()
    end
    self.bossItem = nil
    self:ClearBattleReportTimer()
    self:RemoveTimeCall(self.Update)
    if UIRedDots then
        UIRedDots.removeViewEvent(PanelResNames.UIInvasionBattle)
    end
    if self.highRewardTimer then
        utimer.remove(self.highRewardTimer)
        self.highRewardTimer = nil
    end
    if setTimer then
        utimer.remove(setTimer)
        setTimer = nil
    end
end
function t:Update()
    local dt = 0.1
    local _list = TablePool.Get()
    for k,v in pairs(self.damageItemList) do
        v:Update(dt)
        if v:IsDie() then
            table.insert(_list,v)
        end
    end
    for k,v in pairs(_list) do
        self.damageItemList[v.id] = nil
        table.insert(self.damageCacheList[v.showType],v)
    end
    TablePool.ReleaseDeeper(_list,false)
end
function t:GetUniqueId()
    self.staticId = self.staticId + 1
    return self.staticId
end
---@return InvasionDamageItem
function t:GetDamageItem(isBoss)
    local item
    local _type = isBoss and 1 or 2
    if #self.damageCacheList[_type] > 0 then
        item = table.remove(self.damageCacheList[_type])
        self.damageItemList[item.id] = item
    else
        local id = self:GetUniqueId()
        item = InvasionDamageItem.New(self.fguiObj,id,_type)
        self.damageItemList[id] = item
    end
    item:OnCreate()
    return item
end
function t:InitTeam()
    self:RefreshTeam()
    local data = InvasionHandler.teamData
    self.bossItem:InitBoss(data.bossId,data.bossLv)
end
function t:RefreshTeam()
    local players = TBS.ActorMgr.GetLeaderList()
    local count = table.getn(players)
    local isSingle = count == 1
    isSingle=false
    self.ctrlSingle.selectedIndex = isSingle and 1 or 0
    for i,v in ipairs(self.teamItemList) do
        if players then
            v:SetPlayer(players[i])
        else
            v:SetPlayer(nil)
        end
        if i == 1 then
            v:SetCtrlType(isSingle and 2 or 0)
        end
    end
    self.statisticsItem:InitPlayer()
    self:RefreshTeamSkill()
end
function t:RefreshTeamSkill()
    for k,obj in ipairs(self.teamSkillItemList) do
        local skill = TBS.ActorMgr.GetLeaderSkill(k)
        local ctrlState = obj:GetController("state")
        local numText=obj:GetChild("num")
        numText.text=k
        obj.onClick:Clear()
        if skill then
            local icon = obj:GetChild("Mask"):GetChild("Icon")
            local skillCfg = dataTable.getDataTableByStringId("t_collocationskillshow",skill.skillId)
            if skillCfg then
                ctrlState.selectedIndex = 1
                self:SetIcon(icon,skillCfg.f_SkillIcon,EnumConst.ItemShowType.SKILL)
            else
                ctrlState.selectedIndex = 0
            end
            obj.onClick:Add(function()
                showUI(PanelNames.UITeamSkillDetails,skill.skillId)
            end)
        else
            ctrlState.selectedIndex = 0
        end
    end
end
function t:InitBattlePos()
    local isSingle = false--table.getn(TBS.ActorMgr.GetLeaderList()) == 1
    for i = 1,4 do
        local com = self.teamItemList[i]
        local ox,oy = com:GetListPosInRoot()
        for j = 1,6 do
            local x,y = com:GetTeamItemPos(j)
            x,y = Util.FGUILocalToScreen(self.fguiObj,ox+x,oy+y,0,0)
            x,y = TBS.Battle.ScreenToScenePoint(x,y,0)
            TBS.Battle.SetGroupPosition(i,j,x,y)
        end
        local x1,y1 = com:GetTeamItemPos(1)
        local x2,y2 = com:GetTeamItemPos(6)
        local x = ox + (x1+x2)/2
        local y = oy + (y1+y2)/2
        if i == 1 or not isSingle then
            x,y = Util.FGUILocalToScreen(self.fguiObj,x,y,0,0)
            x,y = TBS.Battle.ScreenToScenePoint(x,y,0)
            TBS.Battle.SetLeaderPosition(i,x,y)
        end
        if i > 1 and isSingle then
            x,y = TBS.Battle.GetLeaderPosition(1)
            TBS.Battle.SetLeaderPosition(i,x,y)
        end
    end
    TBS.Battle.SetBossPosition(self.bossItem:GetWPos())
end
function t:ClickBack()
    closeUI(PanelNames.UIInvasionBattle)
    AudioManager.Play(7)
    UISpeed()
end
function t.PlayScaleReverseDone()
    t.isPlayTranScale = 0
end
function t.PlayScaleReverse()
    t.isPlayTranScale = 2
    if t.transitionScale then
        t.transitionScale:PlayReverse(t.PlayScaleReverseDone)
    end
end
function t.PlayScaleReverseDelay()
    t.isPlayTranScale = 2
    if t.transitionScale then
        t.transitionScale:PlayReverse(1,0.5,t.PlayScaleReverseDone)
    end
end
--region Event
---@param target TBS.Player
---@param attacker TBS.Player
function t:PlayerHpChanged(target,attacker)
    if target:IsBoss() then
        self.bossItem:HitAction()
        if self.isPlayTranScale == 1 then
            self.transitionScale:Stop()
            t.PlayScaleReverseDelay()
        elseif self.isPlayTranScale == 2 then
            self.transitionScale:Play(1,0,1,-1,nil)
            t.PlayScaleReverseDelay()
        else
            self.isPlayTranScale = 1
            self.transitionScale:Play(t.PlayScaleReverse)
        end
    else
        local team = self.teamItemList[target:GetGroupId()]
        if target:IsPlayer() and team then
            team:SetTeamHp(target:GetGroupIndex(),target:GetHp()/target:GetHpMax()*100)
        end
    end
end
---@param target TBS.Player
---@param attack TBS.Player
function t:DamageShow(target,attack,damage,damageType,sourceSkillId,hitX,hitY)
    local item = self:GetDamageItem(target:IsBoss())
    if target:IsBoss() then
        local offset = dataTable.getGlobalString(422)
        hitX = hitX + offset[1]
        hitY = hitY + offset[2]
    end
    item:SetDamage(damage,damageType,sourceSkillId,hitX,hitY)
    item:SetSize(not target:IsBoss())
    self.statisticsItem:Statistics(attack:GetId(),damage)
end
function t:BossReleaseSkill(id,skillId)
    self.bossItem:ReleaseAction(skillId)
end
function t:BattleFinished()
    if self:IsBattleValid() then
        self:TryGetBattleReport()
    end
    --InvasionHandler.ReqInitTeamBoss()
end
--接收到广播队伍变化
function t:OnTeamChange()

end
function t:RefreshTeamState()
    local players=TBS.ActorMgr.GetLeaderList()
    local members=InvasionHandler.teamData.member
    local function isInMembers(playerId)
        for i,v in ipairs(members)do
            if tostring(playerId)==tostring(v.playerId) then
                return true
            end
        end
        return false
    end
    local function isInPlayer(playerId)
        for i,v in ipairs(players)do
            if tostring(playerId)==tostring(v.playerId) then
                return true
            end
        end
        return false
    end
    local teamStates={}
    for i=1,4 do
        local state
        if table.isNullOrEmpty(players[i])then
            state=1
        else
            if isInMembers(players[i].playerId)then
                state=0
            else
                state=2
            end
        end
        table.insert(teamStates,state)
    end
    local function findPos()
        local pos=-1
        for i,v in ipairs(teamStates)do
            if v==1 or v==2 then
                pos=i
                break
            end
        end
        return pos
    end
    for i,v in ipairs(members)do
        if not isInPlayer(v.playerId)then
            local pos=findPos()
            if pos==-1 then
                logError("队伍成员状态计算错误")
                break
            end
            teamStates[pos]=3
        end
    end
    for i,v in ipairs(self.teamItemList) do
        v:SetTeamState(teamStates[i],players[i])
    end
end
function t:BattleRestart()
    self:RefreshTeam()
    self:UpdateSkill()
    self:RefreshTeamState()
    local boss = TBS.ActorMgr.GetBoss()
    if not boss then
        logError("找不到boss")
        return
    end
    self:UpdateBossDesc(boss.modelId)
    self.bossItem:InitBoss(boss.modelId,boss.level)
    self.bossItem:UpdateHP()
    if self:IsBattleValid() then
        self:ShowBattleStart()
    end
end
function t:UpdateBossDesc(id)
    local data=dataTable.getDataTableByStringId("t_herospecial",id)
    local skills={data.f_AtkId,data.f_SkillId,data.f_SkillId2}
    local skillTable=G.dataTable["t_collocationskill"]
    for i,v in ipairs(skills)do
        local info=skillTable[tostring(v)]
        self.bossComs[i][1].text=getLanguage(info.f_Name)
        self.bossComs[i][2].text=getLanguage(info.f_Describe)
    end
end
---@param actor TBS.Player
---@param attacker TBS.Player
function t:ActorDead(actor,attacker)
    if actor:IsPlayer() then
        local team = self.teamItemList[actor:GetGroupId()]
        if team then
            team:SetTeamDead(actor:GetGroupIndex())
        end
    end
end
function t:BattleLoadDone()
    --local image = FairyGUI.Image.New();
    --self.effectLoader:SetNativeObject(image);
    --image.texture = NTexture.New(TBS.CameraMgr.texture);
    --image.blendMode = FairyGUI.BlendMode.One_OneMinusSrcAlpha
    self.effectLoader.texture = NTexture.New(TBS.CameraMgr.texture)
    self.effectLoader.blendMode = FairyGUI.BlendMode.One_OneMinusSrcAlpha
    local scale = 1080/Screen.width
    local scaleY = scale
    local defaultRate = 1920/1080
    local rate = Screen.height/Screen.width
    if rate < defaultRate then
        scaleY = 1920/Screen.height
    end
    self.effectLoader:SetScale(scale,scaleY)
    self:InitBattlePos()
    if self:IsBattleValid() and not InvasionHandler.firstWarStart then
        local data = InvasionHandler.teamData
        TBS.VirtualServer.RequestReport(data.oss,data.devOss, data.warPath)
        InvasionHandler.firstWarStart=true
        self:ClearBattleReportTimer()
    else
        self:RequestReport()
    end

end
function t:ScreenShake(name)
    local transition = self:GetTransition(name)
    if transition then
        transition:Play()
    else
        logError("找不到震屏动效："..name)
    end

end
function t:LeaderReleaseSkill(playerId)
    local leader = TBS.ActorMgr.GetActor(playerId)
    local team = self.teamItemList[leader:GetGroupId()]
    if team then
        team:AllAttack()
    end
    --local skill = TBS.ActorMgr.GetLeaderSkill(leader:GetGroupId())
    self:UpdateSkill()
end
function t:SendUIScreenPosToBattle(groupId,groupIndex)
    local team = self.teamItemList[groupId]
    if team then
        local x,y = team:GetTeamItemPos(groupIndex)
        local ox,oy = team:GetListPosInRoot()
        local sx,sy = Util.FGUILocalToScreen(self.fguiObj,ox + x,oy + y,0,0)
        FireEvent(TBS.Config.Event.GetUIPos,groupId,groupIndex,sx,sy)
    end
end
function t:BattleTurnStart(turn,maxTurn)
    self.turnBar.value = turn/maxTurn * 100
    self.turnText.text = string.format(getLanguage("InvasionBattleNum"),turn,maxTurn)
    self:UpdateSkill()
end
function t:UpdateSkill()
    for i=1,4 do
        local item = self.teamSkillItemList[i]
        if item then
            local skill = TBS.ActorMgr.GetLeaderSkill(i)
            local cdCtrl= item:GetController("CD")
            local cdText= item:GetChild("text_CD")
            local cdBar=item:GetChild("n30")
            if skill and skill.cd>0 then
                cdBar.max=skill.maxCd
                cdBar.value=skill.cd
                cdCtrl.selectedIndex=1
                cdText.text=skill.cd
            else
                cdCtrl.selectedIndex=0
            end
        end
    end

end
function t:InitBarrage()
    showUI(PanelNames.UIBulletChat,3)
    local isShowBarrage=GetPlayerPrefs("IsInvasionChatShowBarrage")
    if isShowBarrage~=nil then
        isShowBarrage=tonumber(isShowBarrage)
    else
        isShowBarrage=0
    end
    self:SetBulletVisible(isShowBarrage==0)
end
function t:SetBulletVisible(state)
    local ui_bullet_chat = CtrlManager.GetCtrl(PanelNames.UIBulletChat)
    if ui_bullet_chat ~= nil then
        if state then
            ui_bullet_chat.bullet_chat.visible=true
        else
            ui_bullet_chat.bullet_chat.visible=false
        end
    end
end
function t:TryGetBattleReport()
    local time=HelperFunc.GetServerTime(false)
    local cd=dataTable.getRow("t_global",454).f_int_value    --毫秒
    local fixedPlayCD=3000
    local offset=InvasionHandler.warStartTime+cd-fixedPlayCD-time
    self:ClearBattleReportTimer()
    --local result=InvasionHandler.teamData.warWin
    local result=InvasionHandler.warResult
    if result==0 then
        result=1
    else
        result=0
    end
    if self:IsBattleValid() then
        self:SetBattleUICtrl(2,result)
    end
    if offset<=0 then
        self.battlePortTimer=utimer.timeCall(function()
            self:RequestReport()
        end,3000,1)
    else
        self.battlePortTimer=utimer.timeCall(function()
            self:RequestReport()
        end,3000+offset,1)
    end
end
function t:SetBattleUICtrl(state,result)
    self.battleUICtrl.selectedIndex=state
    self:ClearBattleStartTimer()
    if state==0 then
        Util.PlayAction(self.battleEft, "idle", false);
        AudioManager.Play(STARTBATTLE_SOUND)
    else
        result=result or 0
        if state==2 then
            local resultCtrl=self.resultComp:GetController("result")
            resultCtrl.selectedIndex=result
            local win=self.resultComp:GetChild("shengli").wrapTarget
            local fail=self.resultComp:GetChild("shibai").wrapTarget
            if result==0 then
                self:PlayResult(win)
            else
                self:PlayResult(fail)
            end
        end
    end
end
function t:ShowBattleStart()
    local flag=false
    local boss = TBS.ActorMgr.GetBoss()
    if boss~=nil then
        flag=InvasionHandler.refLevel~=0 and boss.level-InvasionHandler.refLevel>1
        InvasionHandler.refLevel=boss.level
    end
    if flag then
        self.jumpCtrl.selectedIndex=0
        self.jumpTransition:Play()
    end
    self:SetBattleUICtrl(0)
    self.battleStartTimer=utimer.timeCall(function()
        self:SetBattleUICtrl(1)
    end,1000,1)
    self:ClearJumpTimer()
    self.jumpTimer=utimer.timeCall(function()
        if flag then
            self.jumpCtrl.selectedIndex=1
        end
    end,5000,1)
end
function t:ClearBattleReportTimer()
    if self.battlePortTimer~=nil then
        utimer.remove(self.battlePortTimer)
        self.battlePortTimer=nil
    end
end
function t:ClearBattleStartTimer()
    if self.battleStartTimer~=nil then
        utimer.remove(self.battleStartTimer)
        self.battleStartTimer=nil
    end
end
function t:ClearJumpTimer()
    if self.jumpTimer~=nil then
        utimer.remove(self.jumpTimer)
        self.jumpTimer=nil
    end
end
function t:ClearBarrage()
    closeUI(PanelNames.UIBulletChat)
end
function t:PlayResult(eft)
    if self.resultTimer~=nil then
        utimer.remove((self.resultTimer))
        self.resultTimer=nil
    end
    Util.PlayAction(eft, "start", false);
    self.resultTimer = utimer.timeCall(function ()
        Util.PlayAction(eft, "idle", true);
        self.resultTimer = nil;
    end, 1500);
end
function t:RefreshHookRewardState()
    local stateCtrl=self.btnReward:GetController("state")
    local num=G.dataTable["t_global"][tostring(483)].f_string_value[5]
    local time=InvasionHandler.rewardJudgeTime+HelperFunc.GetServerTime()-InvasionHandler.updateJudgeTime
    if time*1000>=num then
        stateCtrl.selectedIndex=1
    else
        stateCtrl.selectedIndex=0
    end
end

function t:RefreshHighRewardState()
    local highRewardCtrl=self.btnReward:GetController("title")
    local txtCountTime = self.btnReward:GetChild("title")
    local countRemain, highRewardEndTime = logicMgr.InvasionManager.GetInvasionHighRewardInfo()
    local countTime = highRewardEndTime - HelperFunc.GetServerTime()
    if countTime > 0 then
        highRewardCtrl.selectedIndex = 0
        if self.highRewardTimer then
            utimer.remove(self.highRewardTimer)
            self.highRewardTimer = nil
        end
        txtCountTime.text = HelperFunc.GetTimeStr2(countTime)
        self.highRewardTimer =  utimer.timeCall(function()
            countTime = countTime - 1
            if countTime <= 0 then
                countTime = 0
                FireEvent(Config.EventType.InvasionOpenHighReward)
                utimer.remove(self.highRewardTimer)
                self.highRewardTimer = nil
            end
            txtCountTime.text = HelperFunc.GetTimeStr2(countTime)
        end, 1000, -1)
    else
        highRewardCtrl.selectedIndex = 1
    end
    if countTime > 0 then
        self.upRewardCtrl.selectedIndex = 1
    else
        self.upRewardCtrl.selectedIndex = 0
    end
    if countRemain > 0 then
        self.weekNumCtrl.selectedIndex = 0
    else
        self.weekNumCtrl.selectedIndex = 1
    end
    local maxCountPerWeek = G.dataTable["t_global"]["629"].f_string_value or 3
    self.txtRewardUp.text = string.format("剩余次数%s/%s", countRemain, maxCountPerWeek)
end

function t:StartFirstWar()
    print("触发FirstWar:valid"..tostring(self:IsBattleValid()).."firstStart"..tostring(InvasionHandler.firstWarStart))
    if self:IsBattleValid() and not InvasionHandler.firstWarStart then
        InvasionHandler.firstWarStart=true
        local data = InvasionHandler.teamData
        TBS.VirtualServer.RequestReport(data.oss,data.devOss, data.warPath)
        self:ClearBattleReportTimer()
    end
end
--endregion Event
return t